<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Admin extends Admin_Controller
{
	function __construct()
	{
  		parent::Admin_Controller();
		$this->load->module_library('users', 'user_lib');
		$this->load->module_language('users', 'user');
		$this->load->module_helper('users', 'user');
 	}

 	// Admin: Control Panel
 	function index()
	{
		// tong so the da ban
		// tinh thoi gian trong thang
		$time = strtotime("now");
		$month = date("m",$time);
		$year = date("Y",$time);
		$lastofMonth = date("t",$time);
		$first_time = mktime(0,0,0,$month,1,$year);
		$last_time = mktime(23,59,59,$month,$lastofMonth,$year);
		// tinh tong giao dich trong thang
		$this->data->str_mt = $month.'/'.$year;
		$this->data->mtrans =  1;
		$this->data->total_card_msold = 1;
		$this->data->total_card_sold = 1;
		$this->layout->create('ckv_admin/cpanel', $this->data);
	}

	// Admin: Log in
	function login()
	{
		if ($this->user_lib->logged_in()){
			redirect('admin');
		}
		$fields = array(
			'email' 			=> $this->lang->line('email_label'). 'email',
			'password' 			=> $this->lang->line('password_label')
		);
		// Call validation and set rules
		$this->load->library('validation');
	    $rules['email'] = 'required|valid_email';
	    $rules['password'] = 'required';
	    $this->validation->set_rules($rules);
	    $this->validation->set_fields($fields);


	    $return_url = isset($_GET['return_url']) ? $_GET['return_url'] : '';
		$httpReferer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'admin';
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			// If the validation worked, or the user is already logged in
		    if ($this->validation->run()) {
	    		if ($this->_check_login()){
	    			if ($return_url && $return_url != base64_encode('/admin/insufficient_permission')){
						redirect(base64_decode($return_url));
					} else{
						redirect('admin');
					}
	    		}else{
	    			$this->data->error = 'Tài khoản và mật khẩu đăng nhập không chính xác.';
	    		}
			} else {
				$this->data->error = $this->validation->error_string;
			}
		}
		$this->layout->wrapper(FALSE);
	    $this->layout->create('ckv_admin/login', $this->data);
	}

	function logout()
	{
		$this->user_lib->logout();
		redirect('admin/login');
	}

	function insufficient_permission(){
		$this->layout->create('ckv_admin/insufficient_permission');
	}

	// Callback From: login()
	function _check_login()
	{
   		if ($this->user_lib->login($this->input->post('email'), $this->input->post('password')))
	   	{
	     	return TRUE;
	    }
	    else
	    {
	   		$this->validation->set_message('_check_login', $this->lang->line($this->user_lib->error_code));
	    	return FALSE;
	    }
	}
}
?>